package com.dailyblue.example.project.bookstore.user.interceptor;

import com.dailyblue.example.project.bookstore.commons.config.JwtConfig;
import com.dailyblue.example.project.bookstore.commons.exception.NotLoginException;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class IsLoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.info("校验用户是否登陆，token：{}", token);
        if (token == null || "".equals(token)) {
            throw new NotLoginException("用户没有登陆！");
        }
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            throw new NotLoginException("登陆效果已失效！");
        }
        Claims claims = JwtConfig.parseJWT(token);
        log.info("claims:{}", claims);
        String id = claims.get("id").toString();
        String redisToken = stringRedisTemplate.opsForValue().get("LOGIN_TOKEN_" + id);
        log.info("redisToken:{}", redisToken);
        if (!token.equals(redisToken)) {
            throw new NotLoginException("登陆效果已失效！");
        }
        log.info("token显示登陆,name:{}", claims.get("name"));
        Long size = stringRedisTemplate.opsForHash().size(id);
        request.getSession().setAttribute("USER_NAME", claims.get("name"));
        request.getSession().setAttribute("SHOPPING_CART_SIZE", size);
        // 加入购物车使用
        request.getSession().setAttribute("USER_ID", id);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
